package com.ygqh.baby.service.impl;

import com.ygqh.baby.ao.DataStatus;
import com.ygqh.baby.ao.Message;
import com.ygqh.baby.ao.OrderType;
import com.ygqh.baby.mapper.YgUserAddressMapper;
import com.ygqh.baby.model.YgProvinceModel;
import com.ygqh.baby.model.YgShoppingCarModel;
import com.ygqh.baby.model.YgUserAddressModel;
import com.ygqh.baby.po.YgUserAddress;
import com.ygqh.baby.po.YgUserAddressExample;
import com.ygqh.baby.service.TrustoneService;
import com.ygqh.baby.service.YgUserAddressService;
import com.ygqh.baby.utils.IDAuthUtil;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class YgUserAddressServiceImpl implements YgUserAddressService {

    protected final Logger logger = Logger.getLogger(this.getClass());

    @Autowired
    private YgUserAddressMapper ygUserAddressMapper;
    @Autowired
    private TrustoneService trustoneService;

    @Override
    public List<YgUserAddressModel> find(Long userId) {
        return ygUserAddressMapper.selectSuper(userId, null);
    }

    @Override
    public int findCount() {
        YgUserAddressExample example = new YgUserAddressExample();
        example.createCriteria().andStatusEqualTo(DataStatus.Valid.name());
        return ygUserAddressMapper.countByExample(example);
    }

    @Override
    public YgUserAddress findById(Long id, Long userId) {
        YgUserAddressExample example = new YgUserAddressExample();
        example.createCriteria().andStatusEqualTo(DataStatus.Valid.name()).andUserIdEqualTo(userId).andIdEqualTo(id);
        List<YgUserAddress> list = ygUserAddressMapper.selectByExample(example);
        if (list != null && list.size() > 0) {
            return list.get(0);
        }
        return null;
    }

    @Override
    public int save(YgUserAddress ygUserAddress) {
        ygUserAddress.setCreateTime(new Date());
        return ygUserAddressMapper.insertSelective(ygUserAddress);
    }

    @Override
    public int update(YgUserAddress ygUserAddress) {
        ygUserAddress.setUpdateTime(new Date());
        return ygUserAddressMapper.updateByPrimaryKeySelective(ygUserAddress);
    }

    @Override
    public int deleteSoft(Long[] ids, Long userId) {
        Assert.notEmpty(ids);

        YgUserAddressExample example = new YgUserAddressExample();
        example.createCriteria().andIdIn(Arrays.asList(ids));
        YgUserAddress record = new YgUserAddress();
        record.setStatus(DataStatus.Delete);

        return ygUserAddressMapper.updateByExampleSelective(record, example);
    }

    @Override
    public int deleteSoft(Long id, Long userId) {
        return this.deleteSoft(new Long[]{id}, userId);
    }

    @Override
    public YgUserAddressModel findDefaultUserAddress(Long userId, Long userAddressId) {
        List<YgUserAddressModel> result = ygUserAddressMapper.selectSuper(userId, userAddressId);
        if (result != null && result.size() > 0) {
            return result.get(0);
        }
        return null;

    }

    /**
     * 该用户是否存在默认地址
     *
     * @param userId
     * @return
     */
    private Boolean hasDefault(Long userId) {
        YgUserAddressExample example = new YgUserAddressExample();
        example.createCriteria().andStatusEqualTo(DataStatus.Valid.name()).andIsDefaultEqualTo(true).andUserIdEqualTo(userId);
        List<YgUserAddress> list = ygUserAddressMapper.selectByExample(example);
        if (list != null && list.size() >= 1) {
            return true;
        }
        return false;
    }

    /**
     * 重置默认地址
     *
     * @param userId
     * @param isDefault
     * @return
     */
    private int resetDefault(Long userId, Boolean isDefault) {

        int row = 0;

        if (isDefault == null) {
            isDefault = false;
        }
        if (isDefault) {
            YgUserAddressExample example = new YgUserAddressExample();
            example.createCriteria().andUserIdEqualTo(userId);
            YgUserAddress record = new YgUserAddress();
            record.setIsDefault(false);
            row = ygUserAddressMapper.updateByExampleSelective(record, example);
        }
        return row;
    }

    @Override
    public int addUserAddress(Long userId, String receiver, String telPhone, String provinceName, String cityName, String areaName, String address,
                              String postCode, Boolean isDefault) {

        this.resetDefault(userId, isDefault);

        YgUserAddress userAddress = new YgUserAddress();
        userAddress.setUserId(userId);
        userAddress.setReceiver(receiver);
        userAddress.setTelPhone(telPhone);
        userAddress.setProvinceName(provinceName);
        userAddress.setCityName(cityName);
        userAddress.setAreaName(areaName);
        userAddress.setAddress(address);
        userAddress.setPostCode(postCode);
        userAddress.setIsDefault(isDefault);
        int row = this.save(userAddress);
        if (row > 0) {
            return userAddress.getId().intValue();
        }
        return 0;
    }

    @Override
    public int updateUserAddress(Long userId, Long addressId, String receiver, String telPhone, String provinceName, String cityName, String areaName,
                                 String address, String postCode, Boolean isDefault) {
        this.resetDefault(userId, isDefault);

        YgUserAddress userAddress = new YgUserAddress();
        userAddress.setId(addressId);
        userAddress.setReceiver(receiver);
        userAddress.setTelPhone(telPhone);
        userAddress.setProvinceName(provinceName);
        userAddress.setCityName(cityName);
        userAddress.setAreaName(areaName);
        userAddress.setAddress(address);
        userAddress.setPostCode(postCode);
        userAddress.setIsDefault(isDefault);
        return this.update(userAddress);
    }

    @Override
    public YgUserAddressModel findUserAddressById(Long userAddressId, Long userId) {
        List<YgUserAddressModel> list = ygUserAddressMapper.selectSuper(userId, userAddressId);
        if (list != null && list.size() > 0) {

            return list.get(0);
        }
        return null;
    }

    @Override
    public List<YgProvinceModel> findCityList() {

        return ygUserAddressMapper.findCityList();
    }

    @Override
    public int transferUserAddr(Long sourceUserId, Long targetUserId) {
        YgUserAddressExample example = new YgUserAddressExample();
        example.createCriteria().andUserIdEqualTo(sourceUserId);
        YgUserAddress record = new YgUserAddress();
        record.setUserId(targetUserId);
        return ygUserAddressMapper.updateByExampleSelective(record, example);
    }

    @Override
    public Message validateUserAddress(Long userId, Long userAddressId, String identityNo, List<YgShoppingCarModel> carModelList, OrderType orderType) {

        List<Long> supplierIds = carModelList.stream().map(YgShoppingCarModel::getSupplierId).collect(Collectors.toList());

        return validateUserAddressV2(userId, userAddressId, identityNo, supplierIds, orderType);

    }

    @Override
    public Message validateUserAddressV2(Long userId, Long userAddressId, String identityNo, List<Long> supplierIds, OrderType orderType) {

        Map<String, Object> extra = new HashMap<>();
        if (OrderType.CardCoupon.equals(orderType)) {
            extra.put("address", new YgUserAddress(userId, "", "", "", "", "", "", ""));
            extra.put("trustoneOrderFlag", Boolean.FALSE);
            return Message.success(extra);
        }
        YgUserAddress address = this.findById(userAddressId, userId);
        if (address == null) {
            logger.warn("收货地址id有误-->userAddressId:" + userAddressId);
            return Message.error("收货地址id有误", null);
        }
        extra.put("address", address);
        Boolean trustoneOrderFlag = trustoneService.isTrustonerOrder(supplierIds);
        extra.put("trustoneOrderFlag", trustoneOrderFlag);
        if (!trustoneOrderFlag) {
            return Message.success(extra);
        }
        identityNo = StringUtils.isBlank(identityNo) ? IDAuthUtil.decryptIdNo(address.getIdentityNo()) : identityNo;
        if (StringUtils.isBlank(identityNo)) {
            return Message.error("收货人身份证号信息为空", null);
        }
        Message message = IDAuthUtil.auth(identityNo, address.getReceiver());
        if (Message.isSuccess(message)) {
            if (!identityNo.equals(address.getIdentityNo())) {
                this.updateIdentityNoAsync(address.getId(), identityNo);
                address.setIdentityNo(IDAuthUtil.encryptIdNo(identityNo));
            }
            message.setExtra(extra);
            return message;
        }
        return Message.error("实名认证失败", null);
    }

    private void updateIdentityNoAsync(Long id, String identityNo) {
        new Thread(() -> {
            YgUserAddress record = new YgUserAddress();
            record.setId(id);
            record.setIdentityNo(IDAuthUtil.encryptIdNo(identityNo));
            ygUserAddressMapper.updateByPrimaryKeySelective(record);
        }).start();
    }

}
